package com.wry.consumer;

import com.wry.api.SpikeService;
import com.wry.api.impl.SpikeServiceImpl;
import com.wry.entity.Goods;
import com.wry.entity.Order;
import com.wry.enums.OrderStatusEnum;
import com.wry.service.GoodsService;
import com.wry.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <h1> 创建订单-消费者 <h1>
 *
 * @author 魏如元
 * @since 2022/7/18
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "ORDER_CREATE_TOPIC", consumerGroup = "group-create")
public class CreateOrderConsumer implements RocketMQListener<String> {

    @Resource
    private OrderService orderService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private SpikeService spikeService;

    @Override
    public void onMessage(String msg) {
        try {
            final String[] s = msg.split("_");
            String orderId = s[0];
            String goodsId = s[1];
            // 处理订单
            detailWithOrder(orderId,goodsId);
        }catch (Exception e){
            e.printStackTrace();
            log.error("创建订单过程中发生异常："+e.getMessage());
            throw e;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void detailWithOrder(String orderId, String goodsId) {
        log.info("------------开始创建订单---------------");
        final Order orders = orderService.lambdaQuery().eq(Order::getOrderId,orderId).one();
        if (!Objects.isNull(orders)){
            log.warn(orderId+"：订单已存在");
           return;
        }
        // 扣减MySQL中库存
        final Goods goods = goodsService.getById(Long.valueOf(goodsId));
        Integer num = goods.getNum();
        log.info("当前库中库存：{}",num);
        if (num <= 0){
            return;
        }
        goods.setNum(--num);
        goodsService.updateById(goods);
        log.info("扣减后-库中库存：{}",goods.getNum());

        // 同步redis中库存
        spikeService.sync();

        // 创建一条订单
        Order order= new Order();
        order.setStatus(OrderStatusEnum.PAYING.name());
        order.setGoodsId(Long.valueOf(goodsId));
        order.setOrderId(orderId);
        orderService.save(order);
        log.info("---------------订单创建成功！【{}】------------",orderId);
    }



}
